<template>
    <div class="auth-page">
        <div class="decorations">
            <div class="gradient-circle orange"></div>
            <div class="gradient-circle blue"></div>
        </div>

        <div class="auth-container">
            <div class="logo-section">
                <h1 class="logo">技术问答与在线互助论坛系统</h1>
                <p class="slogan">加入技术问答社区</p>
            </div>

            <div class="form-section">
                <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef"
                    @keyup.enter="handleRegister">
                    <el-form-item prop="emailAddress">
                        <el-input v-model="registerForm.emailAddress" placeholder="请输入邮箱" prefix-icon="Message"
                            clearable />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
                            show-password />
                        <div class="password-hint" v-if="registerForm.password">
                            密码强度: <span :class="passwordStrengthClass">{{ passwordStrength }}</span>
                        </div>
                    </el-form-item>
                    <el-form-item prop="passwordRepeat">
                        <el-input v-model="registerForm.passwordRepeat" type="password" placeholder="请确认密码"
                            prefix-icon="Lock" show-password />
                    </el-form-item>
                    <div class="send-code-container">
                        <el-form-item prop="verificationCode" class="flex-grow">
                            <el-input v-model="registerForm.verificationCode" placeholder="请输入邮箱验证码" clearable />
                        </el-form-item>
                        <el-button @click="sendEmailCode" :disabled="isSendingCode || !isEmailValid"
                            :loading="codeSending" class="send-code-btn">
                            {{ isSendingCode ? `${countdown}s后重试` : '获取验证码' }}
                        </el-button>
                    </div>
                    <el-checkbox v-model="agreeTerms" class="mb-6">
                        我已阅读并同意<el-link type="primary" :underline="false">《用户协议》</el-link>
                    </el-checkbox>
                    <el-button type="primary" class="submit-btn" @click="handleRegister" :loading="loading"
                        :disabled="!agreeTerms">
                        注册
                    </el-button>
                    <div class="text-center mt-6 text-sm text-gray-500">
                        已有账号? <el-link type="primary" :underline="false" @click="goToLogin">立即登录</el-link>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { registerService, sendEmailCodeService } from '@/apis/user';

const router = useRouter();
const agreeTerms = ref(false);
const isSendingCode = ref(false);
const codeSending = ref(false);
const countdown = ref(0);
let timer = null;

// 注册表单
const registerForm = ref({
    emailAddress: '',
    password: '',
    passwordRepeat: '',
    verificationCode: ''
});

// 验证邮箱格式
const isEmailValid = computed(() => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(registerForm.value.emailAddress);
});

// 密码强度计算
const passwordStrength = computed(() => {
    if (!registerForm.value.password) return '';
    const hasLower = /[a-z]/.test(registerForm.value.password);
    const hasUpper = /[A-Z]/.test(registerForm.value.password);
    const hasNumber = /\d/.test(registerForm.value.password);
    const hasSpecial = /[^a-zA-Z0-9]/.test(registerForm.value.password);

    const strength = [hasLower, hasUpper, hasNumber, hasSpecial].filter(Boolean).length;
    return ['弱', '中', '强', '非常强'][strength - 1] || '弱';
});

const passwordStrengthClass = computed(() => {
    return {
        'text-red-500': passwordStrength.value === '弱',
        'text-yellow-500': passwordStrength.value === '中',
        'text-blue-500': passwordStrength.value === '强',
        'text-green-500': passwordStrength.value === '非常强'
    };
});

// 表单验证规则
const registerRules = {
    emailAddress: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 8, max: 20, message: '长度在8到20个字符', trigger: 'blur' },
        {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
            message: '需包含大小写字母和数字', trigger: 'blur'
        }
    ],
    passwordRepeat: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const password = registerForm.value.password;
                if (password && value !== password) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    verificationCode: [
        { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
        { min: 4, max: 6, message: '验证码格式不正确', trigger: 'blur' }
    ]
};

const loading = ref(false);
const registerFormRef = ref(null);

// 发送邮箱验证码
const sendEmailCode = async () => {
    try {
        // 验证邮箱格式
        if (!registerForm.value.emailAddress) {
            ElMessage.warning('请输入邮箱地址');
            return;
        }

        if (!isEmailValid.value) {
            ElMessage.warning('请输入有效的邮箱地址');
            return;
        }

        // 防止重复发送
        if (isSendingCode.value) return;

        codeSending.value = true;

        // 调用发送验证码接口
        const response = await sendEmailCodeService({
            emailAddress: registerForm.value.emailAddress
        });
        let reee = response
        if (response.code === 1000) {
            ElMessage.success('验证码已发送至您的邮箱，请查收');
            startCountdown();
        } else {
            ElMessage.warning(response.msg);
        }
    } catch (error) {
        ElMessage.warning(error);
    } finally {
        codeSending.value = false;
    }
};

// 开始倒计时
const startCountdown = () => {
    isSendingCode.value = true;
    countdown.value = 120;

    timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            resetCodeButton();
        }
    }, 1000);
};

// 重置验证码按钮状态
const resetCodeButton = () => {
    clearInterval(timer);
    isSendingCode.value = false;
    countdown.value = 0;
};

// 注册方法
const handleRegister = async () => {
    try {
        // 验证表单
        if (!registerFormRef.value) return;
        const valid = await registerFormRef.value.validate();

        if (!valid) {
            ElMessage.warning('请完善表单信息');
            return;
        }

        if (!agreeTerms.value) {
            ElMessage.warning('请同意用户协议');
            return;
        }

        loading.value = true;
        const response = await registerService(registerForm.value);

        if (response.code === 0) {
            // 使用正则表达式从消息中提取账号
            const accountMatch = response.msg.match(/账号为：(\w+)/);
            const account = accountMatch ? accountMatch[1] : '未知账号';

            ElMessageBox.alert(
                `<div style="text-align: center;">
                    <h3 style="margin-bottom: 16px; color: #4361ee;">注册成功!</h3>
                    <p style="margin-bottom: 8px;">您的账号是: <strong style="color: #3f37c9;">${account}</strong></p>
                    <p style="color: #666; font-size: 14px;">请妥善保管您的账号信息</p>
                </div>`,
                '注册成功',
                {
                    confirmButtonText: '前往登录',
                    dangerouslyUseHTMLString: true,
                    customClass: 'success-message-box',
                    callback: () => {
                        router.push('/forum/login');
                    }
                }
            );
        } else {
            ElMessage.warning(response.msg);
        }
    } catch (error) {
        ElMessage.warning(error);
    } finally {
        loading.value = false;
    }
};

// 跳转到登录页
const goToLogin = () => {
    router.push('/forum/login');
};

onUnmounted(() => {
    resetCodeButton();
});
</script>


<style lang="scss" scoped>
// 添加自定义弹框样式
.success-message-box {
    .el-message-box__content {
        padding: 20px;
    }

    .el-message-box__title {
        font-size: 18px;
        font-weight: bold;
        color: #4361ee;
    }

    .el-message-box__headerbtn {
        top: 15px;
        right: 15px;
    }

    .el-button {
        padding: 10px 20px;
        border-radius: 8px;
        background: linear-gradient(90deg, #4361ee, #3f37c9);
        border: none;
        color: white;

        &:hover {
            opacity: 0.9;
        }
    }
}

.auth-page {
    width: 100vw;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;
    background: #f8f9fa;
    font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;

    .decorations {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 0;
        overflow: hidden;

        .gradient-circle {
            position: absolute;
            border-radius: 50%;
            filter: blur(60px);
            opacity: 0.7;
            transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);

            &.orange {
                width: 500px;
                height: 500px;
                background: linear-gradient(135deg, #f72585 0%, #f8961e 100%);
                left: 10%;
                top: 30%;
            }

            &.blue {
                width: 400px;
                height: 400px;
                background: linear-gradient(135deg, #4361ee 0%, #4cc9f0 100%);
                top: 15%;
                right: 10%;
            }
        }
    }

    .auth-container {
        width: 100%;
        max-width: 480px;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 16px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        padding: 48px;
        z-index: 1;
        backdrop-filter: blur(5px);
        transition: all 0.4s;

        &:hover {
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }

        .logo-section {
            .logo {
                font-size: 36px;
                font-weight: 700;
                margin-bottom: 12px;
                background: linear-gradient(90deg, #4361ee, #3f37c9);
                background-clip: text;
                -webkit-background-clip: text;
                -moz-background-clip: text;
                color: transparent;
                -webkit-text-fill-color: transparent;
                transition: all 0.4s;

                @supports not (background-clip: text) {
                    color: #4361ee;
                    background: none;
                }
            }

            .slogan {
                font-size: 16px;
                color: #6c757d;
                letter-spacing: 0.5px;
            }
        }

        .el-form-item {
            margin-bottom: 24px;
        }

        .password-hint {
            font-size: 12px;
            margin-top: 4px;
            color: #6c757d;
        }

        .submit-btn {
            width: 100%;
            height: 48px;
            font-size: 16px;
            font-weight: 500;
            margin-top: 16px;
            background: linear-gradient(90deg, #4361ee, #3f37c9);
            border: none;
            border-radius: 8px;
            transition: all 0.3s;

            &:hover:not(:disabled) {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
            }

            &:active {
                transform: translateY(0);
            }

            &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }
        }

        .el-input {
            transition: all 0.3s;

            &:hover {
                .el-input__wrapper {
                    box-shadow: 0 0 0 1px rgba(67, 97, 238, 0.3);
                }
            }

            .el-input__wrapper {
                padding: 0 15px;
                height: 48px;
                border-radius: 8px;
                transition: all 0.3s;

                &.is-focus {
                    box-shadow: 0 0 0 1px #4361ee !important;
                }
            }
        }

        .send-code-container {
            display: flex;
            gap: 10px;
            margin-bottom: 24px;

            .flex-grow {
                flex-grow: 1;
            }

            .send-code-btn {
                width: 120px;
                white-space: nowrap;

                &:disabled:not(.is-loading) {
                    background-color: #f5f7fa;
                    color: #c0c4cc;
                }
            }
        }
    }
}

@media (max-width: 600px) {
    .auth-page {
        padding: 20px;

        .auth-container {
            padding: 30px 24px;

            .logo-section {
                margin-bottom: 30px;

                .logo {
                    font-size: 28px;
                }
            }

            .send-code-container {
                flex-direction: column;

                .send-code-btn {
                    width: 100%;
                }
            }
        }
    }
}
</style>